﻿using AwesomeChromeFormUI.Cache;
using System;
using System.Windows.Forms;

namespace AwesomeChromeFormUI.Emitter
{
    public class EventEmitter
    {
        public static void EmitByJs(string eventName, string payload)
        {
            // 因为 Browser 属于 UI 控件，必须在 UI 线程上执行

            Control control = Application.OpenForms[0];

            control.Invoke((MethodInvoker)delegate
            {
                foreach (Form form in Application.OpenForms)
                {
                    bool focused = (bool)form.Invoke(new Func<bool>(() => form.ContainsFocus));

                    if (focused)
                    {

                        GlobalBrowserCache
                        .Cache
                        .GetValueByKey(form.Handle.ToString())
                        .GetBrowser()
                        .MainFrame
                        .ExecuteJavaScriptAsync($"emitter.emit('{eventName}', {payload});");

                        break;
                    }

                }
            });
        }

        public static void EmitByMitt(string eventName, string payload)
        {
            // 因为 Browser 属于 UI 控件，必须在 UI 线程上执行

            Control control = Application.OpenForms[0];

            control.Invoke((MethodInvoker)delegate
            {
                foreach (Form form in Application.OpenForms)
                {
                    bool focused = (bool)form.Invoke(new Func<bool>(() => form.ContainsFocus));

                    if (focused)
                    {

                        GlobalBrowserCache
                        .Cache
                        .GetValueByKey(form.Handle.ToString())
                        .GetBrowser()
                        .MainFrame
                        .ExecuteJavaScriptAsync($"window.$EventBus.emit('{ eventName }', {payload});");

                        break;
                    }

                }
            });
        }
    }
}
